package org.cheetah.spring.xml;

import org.cheetah.spring.xml.factory.SwitchProcessorFactoryBean;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.ManagedList;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class SwitchDefinitionParser extends AbstractSingleBeanDefinitionParser {

	@Override
	protected Class<?> getBeanClass(Element element) {
		return SwitchProcessorFactoryBean.class;
	}

	@Override
	protected void doParse(Element element, ParserContext context,
			BeanDefinitionBuilder bean) {
		NodeList children = element.getChildNodes();
		int count = children.getLength();

		ManagedList<String> caseValue = new ManagedList<String>(count);
		ManagedList<Object> caseThen = new ManagedList<Object>(count);

		bean.addPropertyValue("var", element.getAttribute("var"));

		for (int i = 0; i < count; ++i) {
			Node child = children.item(i);

			if (Element.class.isInstance(child)) {
				Element childEl = (Element) child;

				if ("case".equals(childEl.getLocalName())) {
					caseValue.add(childEl.getAttribute("value"));
					caseThen.add(context.getDelegate().parseListElement(
							childEl, bean.getRawBeanDefinition()));
				} else if ("default".equals(childEl.getLocalName())) {
					bean.addPropertyValue("defaultCaseThen", context
							.getDelegate().parseListElement(childEl,
									bean.getRawBeanDefinition()));
				}
			}
		}

		bean.addPropertyValue("caseValue", caseValue);
		bean.addPropertyValue("caseThen", caseThen);
	}
}
